# run assay against anchovy catches
library("readxl")
library("tidyverse")

anchovy <- read_excel("input/bs_anchovy.xlsx")
sst <- read_csv("output/sst-monthly.csv")

data <- anchovy[,c("year", "crimea_ua_nw")]
names(data) <- c("year", "catch")

data.first <- data[1:16,] # 1992-2007
data.second <- data[17:32,] # 2008-2023

## process first half of data
yrs.first <- data.first$year
for (m in 1:12) {
  print(paste0(">>> Process month: ", m))
  dd <- data.first
  for (i in 1:nrow(sst)) {
    #print(paste0("Process row: ", i))
    row <- sst[i,]
    x <- row$x
    y <- row$y
    xy <- paste0(x, '_', y)
    nm <- names(row)
    for (j in 1:length(row)) {
      name <- nm[j]
      d <- as.Date(name, format="X%Y.%m.%d")
      year <- format(d, "%Y")
      month <- format(d, "%m")
      val <- as.numeric(row[j])
      if (is.na(year) || is.na(month) || is.na(val)) {
        next
      } 
      
      if (as.numeric(month) != m) {
        next
      }
      
      idx <- match(as.integer(year), yrs.first)
      if (is.na(idx)) {
        next
      }
      
      dd[idx, xy] <- val
    }
  }
  # save calculated data 
  write.csv(dd, paste0("output/splited/halfed/data_monthly_first/", m, ".csv"), row.names = F)
}

## process second half of data
yrs.second <- data.second$year
for (m in 1:12) {
  print(paste0(">>> Process month: ", m))
  dd <- data.second
  for (i in 1:nrow(sst)) {
    #print(paste0("Process row: ", i))
    row <- sst[i,]
    x <- row$x
    y <- row$y
    xy <- paste0(x, '_', y)
    nm <- names(row)
    for (j in 1:length(row)) {
      name <- nm[j]
      d <- as.Date(name, format="X%Y.%m.%d")
      year <- format(d, "%Y")
      month <- format(d, "%m")
      val <- as.numeric(row[j])
      if (is.na(year) || is.na(month) || is.na(val)) {
        next
      } 
      
      if (as.numeric(month) != m) {
        next
      }
      
      idx <- match(as.integer(year), yrs.second)
      if (is.na(idx)) {
        next
      }
      
      dd[idx, xy] <- val
    }
  }
  # save calculated data 
  write.csv(dd, paste0("output/splited/halfed/data_monthly_second/", m, ".csv"), row.names = F)
}

